/*
 * usb_dev.c
 *
 *  Created on: 9 Mar 2010
 *      Author: bob
 */

#include "usb.h"
#include "usb_dev.h"

// The one and only USB device handle
usb_dev_handle *dev = NULL;

// PUBLIC
int open_dev(void) {

  usb_init(); 			// initialize the library
  usb_find_busses(); 	// find all busses
  usb_find_devices(); 	// find all connected devices


  if(!(dev = __open_dev())) {
      printf("error: device not found!\n");
      return false;
  }

  if(usb_set_configuration(dev, 1) < 0) {
      printf("error: setting config 1 failed\n");
      usb_close(dev);
      return false;
  }

  if(usb_claim_interface(dev, 0) < 0) {
      printf("error: claiming interface 0 failed\n");
      usb_close(dev);
      return false;
  }

  if(usb_set_altinterface(dev, 0) < 0) {
        printf("error: claiming alternate interface 0 failed\n");
        usb_close(dev);
        return false;
  }

  if(usb_clear_halt(dev, 0x86) < 0) {
          printf("error: clearing halt on 0x86 failed\n");
          usb_close(dev);
          return false;
  }

  if(usb_clear_halt(dev, 0x2) < 0) {
            printf("error: clearing halt on 0x2 failed\n");
            usb_close(dev);
            return false;
  }

  return true;
}

void close_dev(void) {

	usb_release_interface(dev, 0);
	usb_close(dev);
}

int bulk_read(int endpoint, char *buf, int size, int timeout) {
	return usb_bulk_read(dev, endpoint, buf, size, timeout);
}

int bulk_write(int endpoint, char *buf, int size, int timeout) {
	return usb_bulk_write(dev, endpoint, buf, size, timeout);
}

// PRIVATE
usb_dev_handle *__open_dev(void)
{
  struct usb_bus *ubus;
  struct usb_device *udev;

  for(ubus = usb_get_busses(); ubus; ubus = ubus->next)
    {
      for(udev = ubus->devices; udev; udev = udev->next)
        {
          if(udev->descriptor.idVendor == MY_VID
             && udev->descriptor.idProduct == MY_PID)
            {
              return usb_open(udev);
            }
        }
    }
  return false;
}

